/*
 * @Description: 消息
 * @Author: Yong
 * @Date: 2021-10-02 22:52:33
 * @LastEditTime: 2021-10-10 22:35:39
 */
import { Provide, Inject } from "@midwayjs/decorator"
import { Context } from "@midwayjs/koa"
import { InjectEntityModel } from "@midwayjs/orm"
import { Repository } from "typeorm"
import { Messages } from "../entity/Messages.entity"
import { MsgO } from "../interface"
@Provide()
export class MessageService {
    @Inject()
    ctx: Context

    @InjectEntityModel(Messages)
    msgModel: Repository<Messages>

    // 添加一对一消息
    async addMessage(msgInfo: MsgO) {
        const msg = new Messages()
        msg.M_UserID = msgInfo.uid
        msg.M_FriendID = msgInfo.fid
        msg.M_Cont = msgInfo.cont
        msg.M_Types = msgInfo.type
        msg.M_state = msgInfo.state
        await this.msgModel.save(msg)
    }

    // 获取最新的一条消息
    async getLastMessage (uid: string, fid: string) {
        const message = await this.msgModel.createQueryBuilder()
            .where({ M_UserID: uid, M_FriendID: fid })
            .orWhere({ M_FriendID: uid, M_UserID: fid })
            .orderBy('messages.createTime', 'DESC')
            .getOne()
        return message
    }

    // 获取message未读消息数
    async getUnreadMsgCount (uid: string, fid: string) {
        const unreadMsgCount = await this.msgModel.createQueryBuilder()
            .where({ M_UserID: uid, M_FriendID: fid })
            .andWhere({ M_state: 1 })
            .getCount()
        return unreadMsgCount
    }

    // 更新MsgState为已读状态
    async updateMsgState (uid: string, fid: string) {
        await this.msgModel.createQueryBuilder()
            .update(Messages)
            .set({M_state: 0 })
            .where({ M_UserID: fid, M_FriendID: uid })
            .execute()
    }

}
